﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Globals = DotNetNuke.Common.Globals;

using BuSm = VLUNewsBusiness.VLUSitemap;
using BuUtil = VLUNewsBusiness.Utilities;
using DotNetNuke.Security;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Framework;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Skins.Controls;
using DotNetNuke.UI.WebControls;
using System.Collections;
using DotNetNuke.UI.Utilities;

namespace VLUNewsUI.VLUSitemap
{
    public partial class Sitemap : PortalModuleBase
    {
        #region Private Members
        private int _SitemapID = -1;
        private int _ParentID = -1;
        private int _ChildrenCount = -1;
        private string _CommandName = string.Empty;

        #endregion

        #region Private Methods
        void BindingDataGrid(int pParentID = -1)
        {
            ViewState["ParentID"] = pParentID;
            dgdSitemap.DataSource = BuSm.Sitemap.Instance().GetsChildrenExcept(_SitemapID, pParentID);
            Localization.LocalizeDataGrid(ref dgdSitemap, LocalResourceFile);
            dgdSitemap.DataBind();
        }
        void BindingDataList(IList pParents)
        {
            dtlParent.DataSource = pParents;
            dtlParent.DataBind();
        }


        void SetControlValues(Array pModel)
        {
            if (pModel == null)
            {
                txtSitemapName.Text = string.Empty;
                txtURL.Text = string.Empty;
                chbIsSecurity.Checked = false;
                txtSortOrder.Text = string.Empty;
            }
            else
            {
                txtSitemapName.Text = pModel.GetValue(2).ToString();
                txtURL.Text = pModel.GetValue(3).ToString();
                chbIsSecurity.Checked = bool.Parse(pModel.GetValue(4).ToString());
                txtSortOrder.Text = pModel.GetValue(5).ToString();
            }
        }

        #endregion

        #region Event Handlers

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            jQuery.RequestDnnPluginsRegistration();

            cmdDelete.Click += OnDeleteClick;
            cmdUpdate.Click += OnUpdateClick;
            cmdCancel.Click += OnCancelClick;
            dgdSitemap.ItemCommand += OnDataGridSitemap_ItemCommand;
            dgdSitemap.PreRender += OnSitemap_PreRender;
            dtlParent.ItemCommand += OnParent_ItemCommand;

            try
            {
                if ((Request.QueryString["SitemapID"] != null))
                {
                    _SitemapID = Int32.Parse(Request.QueryString["SitemapID"]);
                }
                if (ViewState["ParentID"] == null)
                {
                    if (Request.QueryString["ParentID"] != null)
                        _ParentID = Int32.Parse(Request.QueryString["ParentID"]);
                    ViewState["ParentID"] = _ParentID;
                }
                if (!Page.IsPostBack)
                {
                    string confirmString = Localization.GetString("ConfirmUnRegister", LocalResourceFile);
                    ClientAPI.AddButtonConfirm(cmdDelete, confirmString);

                    IList lstParent;
                    // Create New
                    if (_SitemapID == -1)
                    {
                        lstParent = BuSm.Sitemap.Instance().GetsParentByParentID(_ParentID);
                        cmdDelete.Visible = false;
                        // Get children count of parent sitemap.
                        txtSortOrder.Text = (BuSm.Sitemap.Instance().GetChildrenCount(_ParentID) + 1).ToString();
                    }
                    else
                    {
                        lstParent = BuSm.Sitemap.Instance().GetsParent(_SitemapID);
                        Array sitemap = BuSm.Sitemap.Instance().GetBySitemapID(_SitemapID);
                        SetControlValues(sitemap);
                    }
                    if (lstParent == null)
                        lstParent = new List<KeyValuePair<int, string>>();
                    lstParent.Insert(0, new KeyValuePair<int, string>(-1, Localization.GetString("RootParent", LocalResourceFile)));
                    BindingDataList(lstParent);
                    BindingDataGrid(_ParentID);
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
            // Release Business Object.
            BuSm.Sitemap.Release();
        }

        protected void OnSitemap_PreRender(object sender, EventArgs e)
        {
            if (!(_CommandName.Equals("Up") || _CommandName.Equals("Down")))
                dgdSitemap.SelectedIndex = -1;
        }

        protected void OnParent_ItemCommand(object source, DataListCommandEventArgs e)
        {
            _CommandName = e.CommandName;
            int iSitemapID = Int32.Parse(e.CommandArgument.ToString());
            _ParentID = iSitemapID;
            ViewState["ParentID"] = _ParentID;
            List<KeyValuePair<int, string>> lst = new List<KeyValuePair<int, string>>();
            foreach (DataListItem item in dtlParent.Items)
            {
                CommandButton cmd = (CommandButton)item.Controls[1];
                lst.Add(new KeyValuePair<int, string>(int.Parse(cmd.CommandArgument), cmd.Text));
                if (item == e.Item)
                {
                    break;
                }
            }

            BindingDataList(lst);

            BindingDataGrid(int.Parse(e.CommandArgument.ToString()));
        }

        protected void OnDataGridSitemap_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Select":
                    {
                        OnSelectCommand(source, e);
                        break;
                    }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdUpdate_Click runs when the update Button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// 	[jlucarino]	2/23/2009	Added CreatedByUserID and LastModifiedByUserID
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void OnUpdateClick(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid)
                {
                    int iSortOrder = string.IsNullOrWhiteSpace(txtSortOrder.Text) ? 1 : int.Parse(txtSortOrder.Text);
                    _ParentID = int.Parse(ViewState["ParentID"].ToString());
                    int reslult = BuSm.Sitemap.Instance().Save(_SitemapID, PortalId, _ParentID, txtSitemapName.Text, txtURL.Text, chbIsSecurity.Checked, iSortOrder, UserId);
                    if (reslult != 1) // Error.
                    {
                        DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SitemapSaveError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    }
                    else // Success.
                    {
                        Response.Redirect(Globals.NavigateURL("", "ParentID=" + _ParentID, "SitemapID=" + _SitemapID));
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdDelete_Click runs when the delete Button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void OnDeleteClick(object sender, EventArgs e)
        {
            try
            {
                int reslult = BuSm.Sitemap.Instance().Delete(_SitemapID);
                switch (reslult)
                {
                    case 0:
                    case -1:
                        {
                            DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ErrorSave", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                            break;
                        }
                    case 1: // Success.
                        {
                            _ParentID = int.Parse(ViewState["ParentID"].ToString());
                            Response.Redirect(Globals.NavigateURL("", "ParentID=" + _ParentID, "SitemapID=" + _SitemapID));
                            break;
                        }
                    case 2:
                        {
                            DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ErrorDeleteHaveChild", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                            break;
                        }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdDelete_Click runs when the delete Button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void OnCancelClick(object sender, EventArgs e)
        {
            _ParentID = int.Parse(ViewState["ParentID"].ToString());
            Response.Redirect(Globals.NavigateURL("", "ParentID=" + _ParentID, "SitemapID=" + _SitemapID));
        }

        protected void OnSelectCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                int iSitemapID = Int32.Parse(e.CommandArgument.ToString());
                _ParentID = iSitemapID;
                ViewState["ParentID"] = _ParentID;
                string sSitemapName = e.Item.Cells[2].Text;
                List<KeyValuePair<int, string>> lst = new List<KeyValuePair<int, string>>();
                foreach (DataListItem item in dtlParent.Items)
                {
                    CommandButton cmd = (CommandButton)item.Controls[1];
                    lst.Add(new KeyValuePair<int, string>(int.Parse(cmd.CommandArgument), cmd.Text));
                }
                lst.Add(new KeyValuePair<int, string>(iSitemapID, sSitemapName));

                BindingDataList(lst);
                // Binding data grid.
                BindingDataGrid(iSitemapID);
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        #endregion
    }
}